package com.pshcp.common.config;

import cn.hutool.core.collection.ListUtil;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.oas.annotations.EnableOpenApi;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.AuthorizationScope;
import springfox.documentation.service.HttpAuthenticationScheme;
import springfox.documentation.service.SecurityReference;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;

/**
 * 项目文档配置
 */
@Configuration
@EnableOpenApi
public class Swagger3Config {

    private String version = "1.0";

    @Value("${swagger.enable:true}")
    private boolean swaggerEnable;

    @Bean
    public Docket defaultApi() {
        return new Docket(DocumentationType.OAS_30)
                .groupName("默认")
                .apiInfo(defaultApiInfo())
                .enable(swaggerEnable)
                .securitySchemes(ListUtil.of(tokenScheme()))
                .securityContexts(ListUtil.of(tokenContext()))
                .select()
                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                .paths(PathSelectors.any()).build()/*.forCodeGeneration(true)*/;

    }

    private ApiInfo defaultApiInfo() {
        return new ApiInfoBuilder()
                .title("PSHCP-接口文档")
                .description("接口文档") //服务条款网址
                .version(version).build();
    }

    private HttpAuthenticationScheme tokenScheme() {
        return HttpAuthenticationScheme.JWT_BEARER_BUILDER.name("Authorization").build();
    }

    private SecurityContext tokenContext() {
        return SecurityContext.builder()
                .securityReferences(ListUtil.of(SecurityReference.builder()
                        .scopes(new AuthorizationScope[0])
                        .reference("Authorization").build()))
                .operationSelector(o -> o.requestMappingPattern().matches("/.*")).build();
    }

}